package com.example.geoquiz;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

public class LoginActivity extends AppCompatActivity {
    EditText mUsername, mPasswd;
    Button mLoginBtn;

    private void getRequest(String address) {
        RequestQueue mQueue = Volley.newRequestQueue(LoginActivity.this);
        StringRequest stringRequest = new StringRequest(address,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("TTTT", response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("TTTT", error.getMessage(), error);
                    }
                }
        );
        mQueue.add(stringRequest);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        mUsername = findViewById(R.id.username);
        mPasswd = findViewById(R.id.passwd);
        mLoginBtn = findViewById(R.id.loginButton);

        final RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
        mLoginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String user = mUsername.getText().toString();
                String pwd = mPasswd.getText().toString();
                //String url = "http://192.168.31.15:8080/MyAndroidServer/Servers?username=admin&password=admin";
                String url = "http://192.168.31.15:8080/MyAndroidServer/Servers?username="+user+"&password="+pwd;
                //getRequest(url);

                StringRequest srq = new StringRequest(url, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        Log.d("login", s);
                        if (s.contains("Login success")) {
                            Intent it = new Intent(LoginActivity.this, RecyViewActivity.class);
                            startActivity(it);
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.d("login", volleyError.getMessage());
                    }
                });
                queue.add(srq);
            }
        });
    }
}